3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
23 * Pager for Special:Contributions
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\Rdbms\IResultWrapper
;
28 use Wikimedia\Rdbms\FakeResultWrapper
;
29 use Wikimedia\Rdbms\IDatabase
;
31 class ContribsPager
extends RangeChronologicalPager
{
33 public $mDefaultDirection = IndexPager
::DIR_DESCENDING
;
36 public $namespace = '';
38 public $preventClickjacking = false;
46 protected $mParentLens;
51 protected $templateParser;
53 function __construct( IContextSource
$context, array $options ) {
54 parent
::__construct( $context );
63 foreach ( $msgs as $msg ) {
64 $this->messages
[$msg] = $this->msg( $msg )->escaped();
67 $this->target
= $options['target'] ??
'';
68 $this->contribs
= $options['contribs'] ??
'users';
69 $this->namespace = $options['namespace'] ??
'';
70 $this->tagFilter
= $options['tagfilter'] ??
false;
71 $this->nsInvert
= $options['nsInvert'] ??
false;
72 $this->associated
= $options['associated'] ??
false;
74 $this->deletedOnly
= !empty( $options['deletedOnly'] );
75 $this->topOnly
= !empty( $options['topOnly'] );
76 $this->newOnly
= !empty( $options['newOnly'] );
77 $this->hideMinor
= !empty( $options['hideMinor'] );
79 // Date filtering: use timestamp if available
82 if ( $options['start'] ) {
83 $startTimestamp = $options['start'] . ' 00:00:00';
85 if ( $options['end'] ) {
86 $endTimestamp = $options['end'] . ' 23:59:59';
88 $this->getDateRangeCond( $startTimestamp, $endTimestamp );
90 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
91 // with extra user based indexes or partioning by user. The additional metadata
92 // queries should use a regular replica DB since the lookup pattern is not all by user.
93 $this->mDbSecondary
= wfGetDB( DB_REPLICA
); // any random replica DB
94 $this->mDb
= wfGetDB( DB_REPLICA
, 'contributions' );
95 $this->templateParser
= new TemplateParser();
98 function getDefaultQuery() {
99 $query = parent
::getDefaultQuery();
100 $query['target'] = $this->target
;
106 * This method basically executes the exact same code as the parent class, though with
107 * a hook added, to allow extensions to add additional queries.
109 * @param string $offset Index offset, inclusive
110 * @param int $limit Exact query limit
111 * @param bool $descending Query direction, false for ascending, true for descending
112 * @return IResultWrapper
114 function reallyDoQuery( $offset, $limit, $descending ) {
115 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
122 * This hook will allow extensions to add in additional queries, so they can get their data
123 * in My Contributions as well. Extensions should append their results to the $data array.
125 * Extension queries have to implement the navbar requirement as well. They should
126 * - have a column aliased as $pager->getIndexField()
128 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
129 * - have the ORDER BY specified based upon the details provided by the navbar
131 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
133 * &$data: an array of results of all contribs queries
134 * $pager: the ContribsPager object hooked into
135 * $offset: see phpdoc above
136 * $limit: see phpdoc above
137 * $descending: see phpdoc above
139 $data = [ $this->mDb
->select(
140 $tables, $fields, $conds, $fname, $options, $join_conds
143 'ContribsPager::reallyDoQuery',
144 [ &$data, $this, $offset, $limit, $descending ]
149 // loop all results and collect them in an array
150 foreach ( $data as $query ) {
151 foreach ( $query as $i => $row ) {
152 // use index column as key, allowing us to easily sort in PHP
153 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
165 $result = array_slice( $result, 0, $limit );
167 // get rid of array keys
168 $result = array_values( $result );
170 return new FakeResultWrapper( $result );
173 function getQueryInfo() {
174 $revQuery = Revision
::getQueryInfo( [ 'page', 'user' ] );
176 'tables' => $revQuery['tables'],
177 'fields' => array_merge( $revQuery['fields'], [ 'page_is_new' ] ),
180 'join_conds' => $revQuery['joins'],
183 if ( $this->contribs
== 'newbie' ) {
184 $max = $this->mDb
->selectField( 'user', 'max(user_id)', '', __METHOD__
);
185 $queryInfo['conds'][] = $revQuery['fields']['rev_user'] . ' >' . (int)( $max - $max / 100 );
186 # ignore local groups with the bot right
187 # @todo FIXME: Global groups may have 'bot' rights
188 $groupsWithBotPermission = User
::getGroupsWithPermission( 'bot' );
189 if ( count( $groupsWithBotPermission ) ) {
190 $queryInfo['tables'][] = 'user_groups';
191 $queryInfo['conds'][] = 'ug_group IS NULL';
192 $queryInfo['join_conds']['user_groups'] = [
194 'ug_user = ' . $revQuery['fields']['rev_user'],
195 'ug_group' => $groupsWithBotPermission,
196 'ug_expiry IS NULL OR ug_expiry >= ' .
197 $this->mDb
->addQuotes( $this->mDb
->timestamp() )
201 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
202 // a timestamp offset far in the past such that there are no edits by users with user_ids in
203 // the range, we would end up scanning all revisions from that offset until start of time.
204 $queryInfo['conds'][] = 'rev_timestamp > ' .
205 $this->mDb
->addQuotes( $this->mDb
->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
207 $user = User
::newFromName( $this->target
, false );
208 $ipRangeConds = $user->isAnon() ?
$this->getIpRangeConds( $this->mDb
, $this->target
) : null;
209 if ( $ipRangeConds ) {
210 $queryInfo['tables'][] = 'ip_changes';
212 * These aliases make `ORDER BY rev_timestamp, rev_id` from {@see getIndexField} and
213 * {@see getExtraSortFields} use the replicated `ipc_rev_timestamp` and `ipc_rev_id`
214 * columns from the `ip_changes` table, for more efficient queries.
215 * @see https://phabricator.wikimedia.org/T200259#4832318
217 $queryInfo['fields'] = array_merge(
219 'rev_timestamp' => 'ipc_rev_timestamp',
220 'rev_id' => 'ipc_rev_id',
222 array_diff( $queryInfo['fields'], [
227 $queryInfo['join_conds']['ip_changes'] = [
228 'LEFT JOIN', [ 'ipc_rev_id = rev_id' ]
230 $queryInfo['conds'][] = $ipRangeConds;
232 // tables and joins are already handled by Revision::getQueryInfo()
233 $conds = ActorMigration
::newMigration()->getWhere( $this->mDb
, 'rev_user', $user );
234 $queryInfo['conds'][] = $conds['conds'];
235 // Force the appropriate index to avoid bad query plans (T189026)
236 if ( isset( $conds['orconds']['actor'] ) ) {
237 // @todo: This will need changing when revision_comment_temp goes away
238 $queryInfo['options']['USE INDEX']['temp_rev_user'] = 'actor_timestamp';
239 // Alias 'rev_timestamp' => 'revactor_timestamp' so "ORDER BY rev_timestamp" is interpreted to
240 // use revactor_timestamp instead.
241 $queryInfo['fields'] = array_merge(
242 array_diff( $queryInfo['fields'], [ 'rev_timestamp' ] ),
243 [ 'rev_timestamp' => 'revactor_timestamp' ]
246 $queryInfo['options']['USE INDEX']['revision'] =
247 isset( $conds['orconds']['userid'] ) ?
'user_timestamp' : 'usertext_timestamp';
252 if ( $this->deletedOnly
) {
253 $queryInfo['conds'][] = 'rev_deleted != 0';
256 if ( $this->topOnly
) {
257 $queryInfo['conds'][] = 'rev_id = page_latest';
260 if ( $this->newOnly
) {
261 $queryInfo['conds'][] = 'rev_parent_id = 0';
264 if ( $this->hideMinor
) {
265 $queryInfo['conds'][] = 'rev_minor_edit = 0';
268 $user = $this->getUser();
269 $queryInfo['conds'] = array_merge( $queryInfo['conds'], $this->getNamespaceCond() );
271 // Paranoia: avoid brute force searches (T19342)
272 if ( !$user->isAllowed( 'deletedhistory' ) ) {
273 $queryInfo['conds'][] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0';
274 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
275 $queryInfo['conds'][] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::SUPPRESSED_USER
) .
276 ' != ' . Revision
::SUPPRESSED_USER
;
279 // For IPv6, we use ipc_rev_timestamp on ip_changes as the index field,
280 // which will be referenced when parsing the results of a query.
281 if ( self
::isQueryableRange( $this->target
) ) {
282 $queryInfo['fields'][] = 'ipc_rev_timestamp';
285 ChangeTags
::modifyDisplayQuery(
286 $queryInfo['tables'],
287 $queryInfo['fields'],
289 $queryInfo['join_conds'],
290 $queryInfo['options'],
294 // Avoid PHP 7.1 warning from passing $this by reference
296 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
301 function getNamespaceCond() {
302 if ( $this->namespace !== '' ) {
303 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
304 $eq_op = $this->nsInvert ?
'!=' : '=';
305 $bool_op = $this->nsInvert ?
'AND' : 'OR';
307 if ( !$this->associated
) {
308 return [ "page_namespace $eq_op $selectedNS" ];
311 $associatedNS = $this->mDb
->addQuotes(
312 MWNamespace
::getAssociated( $this->namespace )
316 "page_namespace $eq_op $selectedNS " .
318 " page_namespace $eq_op $associatedNS"
326 * Get SQL conditions for an IP range, if applicable
327 * @param IDatabase $db
328 * @param string $ip The IP address or CIDR
329 * @return string|false SQL for valid IP ranges, false if invalid
331 private function getIpRangeConds( $db, $ip ) {
332 // First make sure it is a valid range and they are not outside the CIDR limit
333 if ( !$this->isQueryableRange( $ip ) ) {
337 list( $start, $end ) = IP
::parseRange( $ip );
339 return 'ipc_hex BETWEEN ' . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
343 * Is the given IP a range and within the CIDR limit?
345 * @param string $ipRange
346 * @return bool True if it is valid
349 public function isQueryableRange( $ipRange ) {
350 $limits = $this->getConfig()->get( 'RangeContributionsCIDRLimit' );
352 $bits = IP
::parseCIDR( $ipRange )[1];
354 ( $bits === false ) ||
355 ( IP
::isIPv4( $ipRange ) && $bits < $limits['IPv4'] ) ||
356 ( IP
::isIPv6( $ipRange ) && $bits < $limits['IPv6'] )
367 public function getIndexField() {
368 // Note this is run via parent::__construct() *before* $this->target is set!
369 return 'rev_timestamp';
375 protected function getExtraSortFields() {
376 // Note this is run via parent::__construct() *before* $this->target is set!
380 function doBatchLookups() {
381 # Do a link batch query
382 $this->mResult
->seek( 0 );
384 $this->mParentLens
= [];
385 $batch = new LinkBatch();
386 $isIpRange = $this->isQueryableRange( $this->target
);
387 # Give some pointers to make (last) links
388 foreach ( $this->mResult
as $row ) {
389 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
390 $parentRevIds[] = $row->rev_parent_id
;
392 if ( isset( $row->rev_id
) ) {
393 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
394 if ( $this->contribs
=== 'newbie' ) { // multiple users
395 $batch->add( NS_USER
, $row->user_name
);
396 $batch->add( NS_USER_TALK
, $row->user_name
);
397 } elseif ( $isIpRange ) {
398 // If this is an IP range, batch the IP's talk page
399 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
401 $batch->add( $row->page_namespace
, $row->page_title
);
404 # Fetch rev_len for revisions not already scanned above
405 $this->mParentLens +
= Revision
::getParentLengths(
407 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
410 $this->mResult
->seek( 0 );
416 function getStartBody() {
417 return "<ul class=\"mw-contributions-list\">\n";
423 function getEndBody() {
428 * Check whether the revision associated is valid for formatting. If has no associated revision
429 * id then null is returned.
432 * @param Title|null $title
433 * @return Revision|null
435 public function tryToCreateValidRevision( $row, $title = null ) {
437 * There may be more than just revision rows. To make sure that we'll only be processing
438 * revisions here, let's _try_ to build a revision out of our row (without displaying
439 * notices though) and then trying to grab data from the built object. If we succeed,
440 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
441 * to extensions to subscribe to the hook to parse the row.
443 Wikimedia\
suppressWarnings();
445 $rev = new Revision( $row, 0, $title );
446 $validRevision = (bool)$rev->getId();
447 } catch ( Exception
$e ) {
448 $validRevision = false;
450 Wikimedia\restoreWarnings
();
451 return $validRevision ?
$rev : null;
455 * Generates each row in the contributions list.
457 * Contributions which are marked "top" are currently on top of the history.
458 * For these contributions, a [rollback] link is shown for users with roll-
459 * back privileges. The rollback link restores the most recent version that
460 * was not written by the target user.
462 * @todo This would probably look a lot nicer in a table.
466 function formatRow( $row ) {
471 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
474 // Create a title for the revision if possible
475 // Rows from the hook may not include title information
476 if ( isset( $row->page_namespace
) && isset( $row->page_title
) ) {
477 $page = Title
::newFromRow( $row );
479 $rev = $this->tryToCreateValidRevision( $row, $page );
481 $attribs['data-mw-revid'] = $rev->getId();
483 $link = $linkRenderer->makeLink(
485 $page->getPrefixedText(),
486 [ 'class' => 'mw-contributions-title' ],
487 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
489 # Mark current revisions
491 $user = $this->getUser();
493 if ( $row->rev_id
=== $row->page_latest
) {
494 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
495 $classes[] = 'mw-contributions-current';
497 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
498 && $page->quickUserCan( 'edit', $user )
500 $this->preventClickjacking();
501 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
504 # Is there a visible previous revision?
505 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
506 $difftext = $linkRenderer->makeKnownLink(
508 new HtmlArmor( $this->messages
['diff'] ),
509 [ 'class' => 'mw-changeslist-diff' ],
512 'oldid' => $row->rev_id
516 $difftext = $this->messages
['diff'];
518 $histlink = $linkRenderer->makeKnownLink(
520 new HtmlArmor( $this->messages
['hist'] ),
521 [ 'class' => 'mw-changeslist-history' ],
522 [ 'action' => 'history' ]
525 if ( $row->rev_parent_id
=== null ) {
526 // For some reason rev_parent_id isn't populated for this row.
527 // Its rumoured this is true on wikipedia for some revisions (T36922).
528 // Next best thing is to have the total number of bytes.
529 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
530 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
531 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
534 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
535 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
538 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
539 $chardiff .= ChangesList
::showCharacterDifference(
544 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
547 $lang = $this->getLanguage();
548 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true, false );
549 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
550 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
551 $d = $linkRenderer->makeKnownLink(
554 [ 'class' => 'mw-changeslist-date' ],
555 [ 'oldid' => intval( $row->rev_id
) ]
558 $d = htmlspecialchars( $date );
560 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
561 $d = '<span class="history-deleted">' . $d . '</span>';
564 # Show user names for /newbies as there may be different users.
565 # Note that only unprivileged users have rows with hidden user names excluded.
566 # When querying for an IP range, we want to always show user and user talk links.
568 if ( ( $this->contribs
== 'newbie' && !$rev->isDeleted( Revision
::DELETED_USER
) )
569 ||
$this->isQueryableRange( $this->target
) ) {
570 $userlink = ' <span class="mw-changeslist-separator"></span> '
571 . $lang->getDirMark()
572 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
573 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
574 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
578 if ( $rev->getParentId() === 0 ) {
579 $flags[] = ChangesList
::flag( 'newpage' );
582 if ( $rev->isMinor() ) {
583 $flags[] = ChangesList
::flag( 'minor' );
586 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
591 // While it might be tempting to use a list here
592 // this would result in clutter and slows down navigating the content
593 // in assistive technology.
594 // See https://phabricator.wikimedia.org/T205581#4734812
595 $diffHistLinks = Html
::rawElement( 'span',
596 [ 'class' => 'mw-changeslist-links' ],
597 // The spans are needed to ensure the dividing '|' elements are not
598 // themselves styled as links.
599 Html
::rawElement( 'span', [], $difftext ) .
600 ' ' . // Space needed for separating two words.
601 Html
::rawElement( 'span', [], $histlink )
605 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
610 $classes = array_merge( $classes, $newClasses );
612 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
617 'diffHistLinks' => $diffHistLinks,
618 'charDifference' => $chardiff,
620 'articleLink' => $link,
621 'userlink' => $userlink,
622 'logText' => $comment,
623 'topmarktext' => $topmarktext,
624 'tagSummary' => $tagSummary,
627 # Denote if username is redacted for this edit
628 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
629 $templateParams['rev-deleted-user-contribs'] =
630 $this->msg( 'rev-deleted-user-contribs' )->escaped();
633 $ret = $this->templateParser
->processTemplate(
634 'SpecialContributionsLine',
639 // Let extensions add data
640 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
641 $attribs = array_filter( $attribs,
642 [ Sanitizer
::class, 'isReservedDataAttribute' ],
646 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
647 // receiving empty rows?
649 if ( $classes === [] && $attribs === [] && $ret === '' ) {
650 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
651 return "<!-- Could not format Special:Contribution row. -->\n";
653 $attribs['class'] = $classes;
655 // FIXME: The signature of the ContributionsLineEnding hook makes it
656 // very awkward to move this LI wrapper into the template.
657 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
661 * Overwrite Pager function and return a helpful comment
664 function getSqlComment() {
665 if ( $this->namespace ||
$this->deletedOnly
) {
666 // potentially slow, see CR r58153
667 return 'contributions page filtered for namespace or RevisionDeleted edits';
669 return 'contributions page unfiltered';
673 protected function preventClickjacking() {
674 $this->preventClickjacking
= true;
680 public function getPreventClickjacking() {
681 return $this->preventClickjacking
;
685 * Set up date filter options, given request data.
687 * @param array $opts Options array
688 * @return array Options array with processed start and end date filter options
690 public static function processDateFilter( array $opts ) {
691 $start = $opts['start'] ??
'';
692 $end = $opts['end'] ??
'';
693 $year = $opts['year'] ??
'';
694 $month = $opts['month'] ??
'';
696 if ( $start !== '' && $end !== '' && $start > $end ) {
702 // If year/month legacy filtering options are set, convert them to display the new stamp
703 if ( $year !== '' ||
$month !== '' ) {
704 // Reuse getDateCond logic, but subtract a day because
705 // the endpoints of our date range appear inclusive
706 // but the internal end offsets are always exclusive
707 $legacyTimestamp = ReverseChronologicalPager
::getOffsetDate( $year, $month );
708 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601
) );
709 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
711 // Clear the new timestamp range options if used and
712 // replace with the converted legacy timestamp
714 $end = $legacyDateTime->format( 'Y-m-d' );
717 $opts['start'] = $start;